$(function () {
	$.init();
	var cache = {};
	var curSku = null;
	var param = parseUrlSearch();

	window.onerror = function (err, url, line, col) {
		$.alert(err);
	}

	$(document).on('click', '.minus', onMinus);
	$(document).on('click', '.add', onAdd);
	$(document).on('click', '.j-buy', onBuy);
	$(document).on('click', '.j-join', joinCar);
	$(document).on('click', '.spec-item .spec-btn', onChoose);
	$(document).on('click', '.j-return', onBack);
	$(document).on('click', '.j-car', goCar);
	$(document).on('click', '.j-apply', onApply);

	renderInfo();
	renderCarCount();


	function fetchInfo(callback) {
		if (!param.id) {
			$.alert('没有id，请联系管理员');
			return;
		}
		$.ajax({
			url: HOST + '/api/spu/get',
			data: {
				spuCode: param.id
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function renderInfo () {
		fetchInfo(function (data) {
			cache = data;
			$('.footer').html(data.status == 2 ? '<div class="tip">团购结束</div><div class="buy j-apply">申请开团</div>' : '<div class="total">合计金额：<span>0</span> RMB</div><div class="join j-join">加入购物车</div><div class="buy j-buy">立即参团</div>');
			var html = getHtml(data);
			$('.content').html(html);
			if ($('.aaa').length > 0) {
				$('.aaa').get(0).click();
			}
		});
	}

	function getHtml(data) {
		data.specificationName || (data.specificationName = {});
		var specHtml = Object.keys(data.specificationName).reduce(function(memo, item) {
			return memo + getSpecHtml({
				label: data.specificationName[item],
				specs: data.skuSpecifications[item],
				value: item
			});
		}, '');
		if (param.id == 100047) {
			data.spuDescription = '<p>套餐包含：</p><p><span></span>国旗纹身贴（4张）</p><p><span></span>8号手摇小国旗（2面，尺寸21cm*14cm）</p><p><span></span>国旗手腕带（1条）</p><p>32国国旗贴纸（1版)</p>'
		}
		if ([100052,100053,100054,100055].indexOf(+param.id) > -1) {
			data.extendInfo = '感谢大家对群服的支持！因原计划4月28日后陆续有球迷追加预定，我们应大家需求延长至<span style="color: #f44336;font-weight:bold;">5月5日</span>，再统一提交制作。白色tee制作周期约3天，黑色tee工艺特殊制作周期约两周。请您耐心等待，不便之处敬请谅解。<img src="https://worldcup.dmpb.com.cn/front/images/chima.jpeg">';
			if (+param.id == 100052) {
				data.extendInfo += '<img src="./images/cloth2.jpg"><img src="./images/cloth3.jpg">';
			}else if (+param.id == 100055) {
				data.extendInfo += '<img src="./images/cloth1.jpg">';
			}
		}

		var arr = [];
		for (var key in data.specificationName) {
			arr.push(data.specificationName[key]);
		}
		return '<img src="'+data.spuImage+'">\
				<div class="wrap">\
					<div class="name">'+data.spuName+'</div>\
					<div><div class="price">团购价：￥<span>--</span></div><div class="oprice"></div></div>\
					<div class="desc">'+(data.spuDescription||'暂无描述')+'</div>\
					<div class="tip">请选择 '+arr.join('、')+'</div>\
				</div>'+specHtml+'<div class="spec-item spec-item-amount">\
					<label>选择数量</label>\
					<div class="val">\
						<div class="num-btn">\
							<span class="iconfont minus">&#xe6fe;</span>\
							<span class="num">1</span>\
							<span class="iconfont add">&#xe6b9;</span>\
						</div>\
					</div>\
				</div>\
				<div class="extendInfo">'+(data.extendInfo||'')+'</div>';
	}

	function getSpecHtml (data) {
		var flag = data.value == 'mark';
		return '<div class="spec-item spec-item-type spec-selectone" data-spec="'+data.value+'" style="border-left-color: #'+Math.floor(Math.random()*0xffffff).toString(16)+';">\
					<label>选择'+data.label+'</label>\
					<div class="val">'+data.specs.reduce(function(memo, item){
						return memo + '<span class="spec-btn '+(flag && item == '不印号'?'aaa':'')+'">' + item + '</span>'
					},'')+'</div>\
				</div>';
	}

	function onMinus (e) {
		var $num = $('.spec-item-amount .num');
		var num = +$num.html();
		num = (num == 1 ? num : num - 1);
		$num.html(num);
		if(curSku) {
			$('.total span').html(+curSku.price * num);
		}
	}

	function onAdd (e) {
		var $num = $('.spec-item-amount .num');
		var num = +$num.html() + 1;
		$num.html(num);
		if(curSku) {
			$('.total span').html(+curSku.price * num);
		}
	}

	function onChoose (e) {
		var $target = $(e.currentTarget);
		$target.toggleClass('active').siblings().removeClass('active');
		var specs = {};
		$('.spec-item .active').forEach(function (item) {
			var $item = $(item);
			specs[$item.closest('.spec-item').data('spec')] = $(item).html();
		});
		var reasons = [];
		for(var key in cache.skuSpecifications) {
			if(!specs[key]) {
				reasons.push(cache.specificationName[key]);
			}
		}
		if(reasons.length > 0) {
			curSku = null;
			$('.wrap .price span').html('--');
			$('.wrap .tip').html('请选择 ' + reasons.join('、'));
			$('.total span').html(0);
			$('.wrap .oprice').html('');
		}else{
			cache.skus.forEach(function (sku) {
				var spec = JSON.parse(sku.specification);
				for(var spec_key in spec) {
					if(spec[spec_key] !== specs[spec_key]) {
						return;
					}
				}
				curSku = sku;
			});
			if(curSku) {
				$('.wrap .tip').html('');
				$('.wrap .price span').html(curSku.price);
				if (curSku.originPrice) {
					$('.wrap .oprice').html('零售价：￥' + curSku.originPrice);
				}
				$('.total span').html((+curSku.price) * (+$('.spec-item-amount .num').html()));
			}else{
				$('.wrap .tip').html('暂无此货');
				$('.wrap .price span').html('--');
				$('.wrap .oprice').html('');
				$('.total span').html(0);
			}
		}
		if (param.id == 100047){
			$('.desc span').html($target.hasClass('active')?$target.html():'');
		}
	}

	function onBuy () {
		if(!curSku) {
			$.alert('请选择规格!');
			return;
		}
		var data = JSON.parse(curSku.specification);
		var spec = [];
		for (var key in data) {
			spec.push(data[key]);
		}
		var details = [{
			sku_image: cache.spuImage,
			sku_name: cache.spuName,
			current_price: curSku.price,
			qty: +$('.spec-item-amount .num').html(),
			sku_code: curSku.skuCode,
			spec: spec.join(' ')
		}];
		sessionStorage.setItem('details', JSON.stringify(details));
		sessionStorage.setItem('param', JSON.stringify(param));
		sessionStorage.setItem('total', +$('.total span').html());
		window.location = './product_sure.html?from=cloth';
	}

	function joinCar() {
		if(!curSku) {
			$.alert('请选择规格!');
			return;
		}
		$.ajax({
			url: HOST + '/api/shopcart/sku/batchUpdate',
			type: 'post',
			data: JSON.stringify({
				openid: SELFID,
				skus: [{
					skuCode: curSku.skuCode,
					qty: +$('.spec-item-amount .num').html()
				}]
				
			}),
			success: function(res) {
				$.alert('成功加入购物车!');
			}
		});
	}

	function onBack () {
		window.location = './product_list.html?category='+param.category
	}

	function goCar () {
		window.location = './product_car.html' + location.search + '&from=cloth';
	}

	function fetchCarCount (callback) {
		$.ajax({
			url: HOST + '/api/shopcart/sku/count',
			data: {
				openid: SELFID
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function renderCarCount () {
		fetchCarCount(function (count) {
			$('.car-tip').show().html(count);
		});
	}

	//申请开团
	function onApply () {
		$.ajax({
			url: HOST + '/api/advice/add',
			data: {
				openid: SELFID,
				advice: '申请开团',
				spu: param.id
			},
			success: function(res) {
				$.alert('申请开团成功！');
			}
		});
	}
})
